<?php
/**
 * Created by Wang.
 * User: nango
 * Date: 2016-06-03
 * Time: 17:11
 */

namespace Wang\Database;


class Model
{
    /**
     * 数据库配置文件
     * @var array
     */
    protected $_config = array();

    /**
     * @var 操作表
     */
    protected $_tb;

    /**
     * @var 数据库对象
     */
    protected $_db;

    /**
     * @var 拼接sql语句
     */
    protected $sql = '';

    /**
     * @var 字段
     */
    protected $fields = '*';

    /**
     * @var string 排序规则
     */
    protected $orderby = '';

    /**
     * @var array sql语句的关键字
     */
    protected $keywords = array();


    function __construct($table = null, $conn = null)
    {
        //导入数据库配置
        $this->_config = load_config(__ROOT__.'/Wang/Common/config.php');
        $conn_type = $conn ? '\Wang\Database\Db' . ucfirst(strtolower($conn)) : '\Wang\Database\Db' . ucfirst(strtolower($this->_config['type']));
        $this->_db = $conn_type::getInstance($this->_config);

        $table && $this->_tb = $this->_config['prefix'].$table;
    }

    /**
     * 查询
     * @return $this
     *
     */
    function select()
    {
        $this->keywords['type'] = "SELECT";
        return $this;
    }

    /**
     * 更新
     * @return $this
     *
     */
    function update()
    {
        $this->keywords['type'] = "UPDATE";
        return $this;
    }

    /**
     * 删除
     * @return $this
     *
     */
    function delete()
    {
        $this->keywords['type'] = "DELETE";
        return $this;
    }

    /**
     * 插入
     * @return $this
     *
     */
    function insert()
    {
        $this->keywords['type'] = "INSERT";
        return $this;
    }

    /**
     * 拼接查询字段信息
     * @param null $fields
     * @return $this
     */
    function fields($fields = '')
    {
        if (!$fields) {
            $fieldsN = '*';
        } elseif (is_string($fields)) {
            $fieldsN = $fields;
        } elseif (is_array($fields)) {
            $fieldsN = implode(',', $fields);
        }

        $this->keywords['fields'] = $fieldsN;
        return $this;
    }

    /**
     * 插入操作 字段值
     * @param null $fields
     * @return $this
     */
    function values($values = '')
    {
        if ($values) {
            $valuesn = $values;
        } elseif (is_array($values)) {
            $valuesn = implode(',', $values);
        }

        $this->keywords['values'] = $valuesn;
        return $this;
    }

    /**
     * 查询条件
     * @param string $condition
     * @return $this
     */
    function where($condition = ''){
        $this->keywords['where'] = ' WHERE '.$condition.' ';
        return $this;
    }

    /**
     * 更新的字段
     * @param array $arr
     */
    function set($arr = array()){
        $this->keywords['set'] = ' SET ';
        foreach($arr as $key => $val){
            $this->keywords['set'] .= $key.'=\''.$val.'\', ';
        }
        return $this;
    }

    /**
     * 排序
     * @param string $sort 排序规则
     * @return $this
     */
    function orderBy($sort = '')
    {
        if ($sort) $this->keywords['orderby'] = 'ORDER BY ' . $sort;

        return $this;
    }

    //TODO
    function leftJoin($table)
    {

    }

    /**
     * 执行查询
     * @param null $sql
     * @return $this
     */
    function query($sql = '')
    {
        if ($sql) {
            $sqli = $sql;
        } else {
            //拼接数据操作语句
            switch ($this->keywords['type']) {
                case 'SELECT':
                    $sqli = 'SELECT ';
                    $sqli .= isset($this->keywords['fields']) ? $this->keywords['fields'] : '*';
                    $sqli .= ' FROM ' . $this->_tb;
                    $sqli .= isset($this->keywords['where']) ? $this->keywords['where'] : '';
                    $sqli .= isset($this->keywords['orderby']) ? $this->keywords['orderby'] : '';
                    break;
                case 'UPDATE':
                    $sqli = 'UPDATE ' . $this->_tb;
                    $sqli .= isset($this->keywords['set']) ? substr($this->keywords['set'], 0 ,-2) : '';
                    $sqli .= isset($this->keywords['where']) ? $this->keywords['where'] : '';
                    break;
                case 'DELETE':
                    $sqli = 'SELECT FROM ' . $this->_tb;
                    $sqli .= isset($this->keywords['where']) ? $this->keywords['where'] : '';
                    break;
                case 'INSERT':
                    $sqli = 'INSERT INTO ' . $this->_tb;
                    $sqli .= isset($this->keywords['fields']) ?  ' ('.$this->keywords['fields'].') ' : '';
                    $sqli .= 'VALUES('.$this->keywords['values'].')';
                    break;
                default :
                    die('缺少必要参数！');
            }
        }
        $this->sql = $sqli;
        $this->_db->query($this->sql);
        return $this;
    }

    /**
     * @return int 返回受影响的行数
     */
    function affectedRows(){
        return $this->_db->affectRows();
    }

    /**
     * @return array
     * 获取全部结果集
     */
    function getAll()
    {
        return $this->_db->fetchAll();
    }

    function stmtGet($sql, $where){
        return $this->_db->prepare($sql, $where);
    }

}